import { createRouter, createWebHistory } from "vue-router";
import Home from "../views/Home.vue";
import store from "../store/index.js";
import { modules } from "./modules.js";

const routes = [
  {
    path: "/",
    name: "Home",
    redirect: "/dashboard",
    component: Home,
    children: [
      {
        path: "/dashboard",
        name: "dashboard",
        meta: { title: "系统首页" },
        component: () => import("../views/Dashboard.vue"),
      },
      {
        path: "/user",
        name: "user",
        meta: { title: "个人中心" },
        component: () => import("../views/user/index"),
      },
    ],
  },
  {
    path: "/login",
    name: "Login",
    meta: { title: "登录" },
    component: () => import("../views/Login.vue"),
  },
  {
    path: "/:pathMatch(.*)*",
    name: "404",
    meta: { title: "找不到页面" },
    component: () => import("../views/404.vue"),
  },
];

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
});

router.beforeEach(async (to, from, next) => {
  document.title = ` 铂时 | ${to.meta.title}`;
  const role = sessionStorage.getItem("Token");

  if (!role) {
    if (to.path !== "/login") {
      next("/login");
    } else {
      next();
    }
  } else {
    // 检查权限是否已加载
    if (store.state.permissions && store.state.permissions.length > 0) {
      // 权限已存在，直接放行
      // console.log(8888, store.state.permissions)
      next();
    } else {
      try {
        // 调用getPermissions获取权限
        const permissions = await store.dispatch("getPermissions");

        // 将权限路由添加到第一个路由的children中
        if (permissions && permissions.length > 0) {
          const homeRoute = router
            .getRoutes()
            .find((route) => route.name === "Home");

          if (homeRoute) {
            // 动态添加权限路由到Home路由的children中
            addPermissionRoutes(permissions);
            // console.log(router, 12121)
          }
        }
        next(to.fullPath);
      } catch (error) {
        console.error("获取权限失败:", error);
        next();
      }
    }
  }
});

// 动态添加权限路由的函数
function addPermissionRoutes(permissions) {
  // 获取所有有权限的路径
  const permissionPaths = getAllPermissionPaths(permissions);

  // 从modules中筛选出有权限的路由
  const allowedRoutes = modules.filter((route) => {
    // return permissionPaths.includes(route.path)
    return permissionPaths.some((it) => it == route.path);
  });
  // console.log(permissionPaths, allowedRoutes, 898989)
  // 添加筛选后的路由到Home路由的children中
  allowedRoutes.forEach((route) => {
    router.addRoute("Home", route);
  });
  router.options.routes[0].children.push(...allowedRoutes);
}

// 递归获取所有权限路径
function getAllPermissionPaths(permissions) {
  let paths = [];

  permissions.forEach((permission) => {
    if (permission.path) {
      paths.push(permission.path);
    }

    // 如果有子权限，递归获取
    if (permission.children && permission.children.length > 0) {
      paths = paths.concat(getAllPermissionPaths(permission.children));
    }
  });

  return paths;
}

export default router;
